<!-- 在这个文件对每个tab对应的列表进行渲染 -->
<template>
	<view class="content">
		<!-- 这里设置了z-paging加载时禁止自动调用reload方法，自行控制何时reload（懒加载）-->
		<!--  :enable-back-to-top="currentIndex===tabIndex" 在微信小程序上可以多加这一句，因为默认是允许点击返回顶部的，但是这个页面有多个scroll-view，会全部返回顶部，所以需要控制是当前index才允许点击返回顶部 -->
		<z-paging ref="paging" v-model="dataList" @query="queryList" :fixed="false" :auto="true">
			<view class="" slot="top"  style="background-color: #FFFFFF;">
				<u-navbar :border-bottom="false" title="红包明细" :title-size="36" :title-bold="true" :title-color="textColor" >
				</u-navbar>
				<view class="detials-top">
					<image :src="shopInfo.logoUrl?shopInfo.logoUrl:defaultLogo" mode="" class="details-logo"></image>
					<view class="u-text-center u-font-34" style="font-weight: bold;">{{shopInfo.brandOwnerName}}</view>
					<view class="u-text-center u-font-40" style="font-weight: bold;margin: 40rpx 0 60rpx;">￥{{shopInfo.balance}}</view>
					<!-- 	<view class="u-p-l-35 u-p-r-35 u-m-b-20">
						<u-input v-model="detailsTypeLabel" placeholder="选择类型" type="select" :height="80" @click="detailsTypeShow=true" class="select-style"/>
					</view> -->
					<view class="u-p-l-35 u-p-r-35 u-flex u-m-b-20" v-if="isTransferAccounts">
						<view class="operate-style u-flex u-p-l-15  " @click="openTransferFn(false)">
							<text class="iconfont icon-tuikuan1 u-m-r-50 " style="color: #65CAFF;font-size: 40rpx;"></text>
							<text style="color: #65CAFF;">转账至商家</text>
						</view>
						<view class="operate-style  u-flex u-p-l-15 u-m-l-20" @click="openTransferFn(true)">
							<text class="iconfont icon-zhuanzhang u-m-r-50 " style="color: #ff551a;font-size: 40rpx;"></text>
							<text style="color: #ff551a;">退回品牌商</text>
						</view>
					</view>
					<view class="u-p-l-35 u-p-r-35 u-flex u-m-b-20">
						<view class="select-style u-flex u-row-between" @click="openAccountTypeFn()">
							<text :style="{color:detailsTypeLabel?'#333':'#999'}">{{detailsTypeLabel||'类型'}}</text>
							<u-icon name="arrow-down-fill" :color="detailsTypeLabel?'#333':'#999'"></u-icon>
						</view>
						<view class="select-style  u-flex u-row-between u-m-l-20" @click="incomeTypeShow=true">
							<text :style="{color:incomeLabel?'#333':'#999'}">{{incomeLabel||'收入/支出'}}</text>
							<u-icon name="arrow-down-fill" :color="incomeLabel?'#333':'#999'"></u-icon>
						</view>
					</view>
					<view class="u-p-l-35 u-p-r-35 u-flex u-m-b-20">
						<view class="select-style u-flex u-row-between" @click="detailsStartShow=true">
							<text :style="{color:detailsStartLabel?'#333':'#999'}">{{detailsStartLabel||'起始时间'}}</text>
							<u-icon name="arrow-down-fill" :color="detailsStartLabel?'#333':'#999'"></u-icon>
						</view>
						<view class="select-style  u-flex u-row-between u-m-l-20" @click="detailsEndShow=true">
							<text :style="{color:detailsEndLabel?'#333':'#999'}">{{detailsEndLabel||'结束时间'}}</text>
							<u-icon name="arrow-down-fill" :color="detailsEndLabel?'#333':'#999'"></u-icon>
						</view>
					</view>
				
				</view>
				
				
			</view>
			<!-- 如果希望其他view跟着页面滚动，可以放在z-paging标签内 -->
		
			<view class="u-p-l-35 u-p-r-35" style="background-color: #FFFFFF;" v-for="item in dataList" :key="item.id">
				<view class="u-flex u-row-between u-p-t-35 u-p-b-35" style="border-bottom: 1px solid #EEEEEE;" @click="goOrderDetails(item.isSeller,item.outerChainId)">
					<view class="">
						<view class="u-m-b-20 u-font-30" style="font-weight: bold;">
							{{item.accountType}}
							<u-icon name="arrow-right" v-if="item.accountOuterChainType == 0"></u-icon>
						</view>
						<view class="u-font-24" style="color: #999999;">
							往来单位：{{item.transferShopName}}
						</view>
						<view class="u-font-24" style="color: #999999;">
							{{$mHelper.parseTime(item.createdTime,'{y}-{m}-{d} {h}:{i}')}}
						</view>
					</view>
					<view class="">
						<view class="u-m-b-44 u-text-right u-font-30" :style="{'fontWeight': 'bold','color':item.amount<0?'#FF551A':'#333333'}">
							{{item.amount}}元
						</view>
						<view class="u-text-right u-font-24" style="color: #999999;">
							红包余额 {{item.currentBalance}}元
						</view>
					</view>
				</view>
			
			</view>
		</z-paging>
		<u-select v-model="detailsTypeShow" :list="typeList" @confirm="typeChangeFn" @cancel="typeCancelFn"></u-select>
		<u-select v-model="incomeTypeShow" :list="incomeList" @confirm="incomeChangeFn" @cancel="incomeCancelFn"></u-select>
		<u-picker v-model="detailsStartShow" mode="time" :params="params" @confirm="startTimeChangeFn" @cancel="startTimeCancelFn"></u-picker>
		<u-picker v-model="detailsEndShow" mode="time" :params="params" @confirm="endTimeChangeFn" @cancel="endTimeCancelFn"></u-picker>
		<!-- 账户余额popup -->
		<u-popup v-model="transferShow" :closeable="true" mode="bottom" >
			<view class="box-padding" style="height: 700rpx;background-color: #FFFFFF;">
				<h3 class="u-text-center u-m-b-20">{{transactionType?'退回品牌商':'转账至商家' }}</h3>
				<view class="" v-if="!submitTransferLoading">
					<view class="u-p-t-10 u-p-b-10 u-p-l-20 u-p-r-20" style="" >
						<view class="u-m-t-40 u-m-b-40" >
							<view v-if="!transactionType">
								<view class="u-font-28 u-flex u-m-t-30 u-m-b-20" style="border-bottom: 1px solid #eee;">
									企业编码
									<input type="number" v-model="useShopNo" 
									placeholder="请输入企业编码"
									 style="margin-left: 20rpx;padding: 10rpx 0;"
									 @input="$u.debounce(identifyShopNo, 500)"  
									 />
								</view>
								<view class="u-font-28 u-flex u-row-between" v-if="useShopNo!=''&&shopNameByNo!=''">
									<text :style="{color:shopNameByNo==='无效的企业编码'?'#ff551a':'#666'}">{{shopNameByNo}}</text>
								</view>
							</view>
							<view v-else class="u-font-28 u-flex u-m-t-30 u-m-b-20 u-p-b-14" style="border-bottom: 1px solid #eee;">
								退回至&nbsp;&nbsp;&nbsp;【{{shopInfo.brandOwnerName}}】
							</view>
							<view class="u-font-28 u-flex u-m-t-30 u-m-b-20" style="border-bottom: 1px solid #eee;">
								{{transactionType?'退还金额':'转账金额'}} ￥
								<input type="number" v-model="useAmount" 
								placeholder="请输入金额"
								 style="margin-left: 20rpx;padding: 10rpx 0;"
								 @input="useAmountInputFn(useAmount,shopInfo.balance)"  
								 @blur="useAmountBlurFn(useAmount,shopInfo.balance)"
								 />
							</view>
							<view class="u-font-28 u-flex u-row-between">
								<view>
									{{transactionType?'可退还余额':'可转账余额'}} ￥{{shopInfo.balance}}
								</view>
								<view  style="color: #FF551A;" @click="useAllTotal(shopInfo.balance)">
									全部使用
								</view>
							</view>
						</view>
					
					</view>
					<button type="default" class="u-m-t-28" @click="confimRedPackageFn" style="background-color: #FFBB1A;border: none;border-radius: 60rpx;">确定</button>
				</view>
				<view class="u-flex u-row-center" v-else style="height: 400rpx;flex-direction: column;">
					<u-loading mode="circle" color="#ff551a" size="44"></u-loading>
					<view class="u-text-center u-font-26 u-m-t-20" style="color:#999;">正在转账中...</view>
				</view>
			</view>
		</u-popup>
		<u-modal v-model="timeTipShow" :show-cancel-button="false"  :content="timeContent" confirm-text="确定"  ></u-modal>
		
	</view>
</template>

<script>
	// import {parseTime} from '@/utils/helper.js'
	import { useShopStore } from '@/store/shop.js';
	import { useUserStore } from '@/store/user.js';
	import { mapState } from 'pinia';
	
	export default {
		data() {
			return {
				
				dataList: [],
				firstLoaded: false,
				detailsTypeLabel:'',
				detailsStartLabel:'',
				detailsEndLabel:'',
				detailsType:'',
				detailsStart:'',
				detailsEnd:'',
				incomeLabel:'',
				incomeType:'',
				detailsTypeShow:false,
				detailsStartShow:false,
				detailsEndShow:false,
				incomeTypeShow:false,
				accountOuterChainType:['支付订单','核销优惠券','官方赠送','奖励金额'],
				typeList:[],
				incomeList:[
					{
						value: true,
						label: '收入'
					},
					{
						value: false,
						label: '支出'
					},
					
				],
				shopInfo:{},
				params:{
					year: true,
					month: true,
					day: true,
					hour: true,
					minute: true,
					second: true,
					// 选择时间的时间戳
					timestamp: true,
				},
				transferShow:false,
				useAmount:'',
				useShopNo:'',
				shopNameByNo:'',
				submitTransferLoading:false,
				transactionType:false,
			}
		},
		onLoad(options){
			this.shopInfo = JSON.parse(options.data);
			
			this.getAccountTypeList();
		},
		computed:{
			...mapState(useShopStore, {storeShop: 'shop'}),
			...mapState(useUserStore, ['isTransferAccounts'])
		},
		methods: {
			goOrderDetails(isSeller,id){
				if(isSeller!==null){
					if(!isSeller){
						this.$mRouter.push({ route: '/pages/purchase/order/xiangqing?id=' + id })
					}else{
						this.$mRouter.push({ route: '/pages/sale/order/xiangqing?id=' + id })
					}
				}
					
			},
			async identifyShopNo(){
				if(this.useShopNo === ''){
					this.shopNameByNo = '';
					return false;
				}
				this.shopNameByNo = '正在识别...';
				const res = await this.$newHttp.get('api/v1.3/Shop/GetShopByNumber', { params: {shopNo:this.useShopNo} } );
				if(res.code  === 200){
					this.shopNameByNo = `转账至企业【${res.data.name}】`;
				}else if(res.code === 400){
					this.shopNameByNo ='无效的企业编码'
				}else{
					this.shopNameByNo ='请求错误'
				}
			},
			async getAccountTypeList(){
				const res = await this.$newHttp.get('api/v1.3/AccountBook/GetAccountChainTypes' );
				if(res.code  === 200){
					this.typeList = res.data.map(item=>{
						return {value:item.value,label:item.description}
					})
				}else{
					this.typeList = [];
				}
			},
			async openAccountTypeFn(){
				if(this.typeList.length === 0){
					await this.getAccountTypeList();
				};
				this.detailsTypeShow=true;
			},
			openTransferFn(flag){
				if(this.shopInfo.balance<=0){
					this.$u.toast('当前余额不支持此操作~');
					return false;
				}
				this.useAmount = '';
				this.shopNameByNo = '';
				this.useShopNo = '';
				this.transactionType = flag;
				this.transferShow = true;
			},
			// 使用余额的限制
			useAmountInputFn(value,maxValue,index){
				if(value>maxValue){
					this.$nextTick(function(){
						this.useAmount = Number(maxValue).toFixed(2);
					})
				}
			},
			// 使用余额的限制
			useAmountBlurFn(value,maxValue,index){
				if(value>maxValue){
					this.$nextTick(function(){
						this.useAmount = Number(maxValue).toFixed(2);
					})
				}else{
					this.$nextTick(function(){
						this.useAmount = Number(value).toFixed(2);
					})
				}
			},
			useAllTotal(maxValue,index){
				this.useAmount = Number(maxValue).toFixed(2);
			},
			// 使用红包
			async confimRedPackageFn(){
				this.submitTransferLoading = true;
				if(this.useShopNo ===''&&!this.transactionType){
					this.submitTransferLoading = false;
					this.$u.toast('企业编码不得为空~')
					return false;
				}
				if(this.useAmount ===''){
					this.submitTransferLoading = false;
					this.$u.toast('金额不得为空~')
					return false;
				}
				let params = {
					brandOwnerId:this.shopInfo.brandOwnerId,
					payeeShopNo:this.transactionType?this.shopInfo.shopNo:this.useShopNo,
					amount:this.useAmount,
					type:this.transactionType?'refund':'immediate'
				}
				const res = await this.$newHttp.put('api/v1.3/AccountBook/TransferAccounts', params );
				this.submitTransferLoading = false;
				let msg = this.transactionType?'退回':'转账';
				if(res.code === 200){
					this.transferShow = false;
					this.$u.toast(msg+'成功');
					this.shopInfo.balance = this.shopInfo.balance-this.useAmount;
					this.$refs.paging.reload();
				}else{
					this.$u.toast(msg+'失败，错误信息：'+res.erroMessage);
				}
			},
			incomeChangeFn(data){
				this.incomeLabel = data[0].label;
				this.incomeType = data[0].value;
				this.$refs.paging.reload();
			},
			incomeCancelFn(){
				this.incomeLabel = '';
				this.incomeType = '';
				this.$refs.paging.reload();
			},
			typeChangeFn(data){
				this.detailsTypeLabel = data[0].label;
				this.detailsType = data[0].value;
				this.$refs.paging.reload();
			},
			typeCancelFn(){
				this.detailsTypeLabel = '';
				this.detailsType = '';
				this.$refs.paging.reload();
			},
			// 计算两个时间段相差天数
			getDaysBetween(startDate, enDate) {
			  const sDate = Date.parse(startDate)
			  const eDate = Date.parse(enDate)
			  if (sDate > eDate) return 0    //开始日期大于结束日期，返回0
			  if (sDate === eDate) return 1  //如果日期相同 返回一天 
			  return (eDate - sDate) / (24 * 60 * 60 * 1000)
			},
			startTimeChangeFn(data){
				let dateStr = data.year+'-'+data.month+'-'+data.day+' '+data.hour+':'+data.minute+':'+data.second;
				let dateStr2 = data.year+'-'+data.month+'-'+data.day+' '+data.hour+':'+data.minute;
				this.detailsStartLabel = dateStr2;
				this.detailsStart = dateStr;
				this.$refs.paging.reload();
				
			},
			startTimeCancelFn(){
				this.detailsStartLabel = '';
				this.detailsStart = '';
				this.$refs.paging.reload();
			},
			endTimeChangeFn(data){
				let dateStr = data.year+'-'+data.month+'-'+data.day+' '+data.hour+':'+data.minute+':'+data.second;
				let dateStr2 = data.year+'-'+data.month+'-'+data.day+' '+data.hour+':'+data.minute;
				this.detailsEndLabel = dateStr2;
				this.detailsEnd = dateStr;
			
				this.$refs.paging.reload();
			},
			endTimeCancelFn(){
				this.detailsEndLabel = '';
				this.detailsEnd = '';
				this.$refs.paging.reload();
			},
			// 余额变动列表上拉加载下拉刷新
			async queryList(pageNo, pageSize) {
				//组件加载时会自动触发此方法，因此默认页面加载时会自动触发，无需手动调用
				//这里的pageNo和pageSize会自动计算好，直接传给服务器即可
				//模拟请求服务器获取分页数据，请替换成自己的网络请求
				const params = {
					pageIndex: pageNo,
					pageSize: pageSize,
					shopId:this.storeShop.id,
					BrandOwnerId:this.shopInfo.brandOwnerId,
				}
				if(this.detailsType!==''){
					params.OuterChainType = this.detailsType;
				}
				if(this.incomeType!==''){
					params.Income = this.incomeType;
				}
				if(this.detailsStart!==''){
					params.BeginTime = this.detailsStart;
				}
				if(this.detailsEnd!==''){
					params.EndTime = this.detailsEnd;
				}
				uni.showLoading({
					title: 'loading...',
					mask: false
				});
				const res = await this.$newHttp.get('api/AccountBook/SearchAccountBookDetails', { params: params } );
				uni.hideLoading({
					title: 'loading...'
				})
				if(res.code === 200){
					this.$refs.paging.complete(res.data.list);
					this.firstLoaded = true;
				}else{
					this.$refs.paging.complete(false);
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	@import '@/static/iconfont/iconfont.css';
	/* 注意:父节点需要固定高度，z-paging的height:100%才会生效 */
	.content {
		height: 100%;
		.detials-top{
			.details-logo{
				width: 80rpx;
				height: 80rpx;
				margin: 70rpx auto 35rpx;
				display: block;
				border-radius: 50%;
			}
			.select-style{
				background-color: #EEEEEE;
				box-sizing: border-box;
				padding: 0 20rpx !important;
				border-radius: 10rpx;
				height: 80rpx;
				flex: 1;
				line-height: 80rpx;
			}
			.operate-style{
				height: 80rpx;
				flex: 1;
				line-height: 80rpx;
				border-radius: 33px;
				&:nth-of-type(1){
					color:#65CAFF;
					border: 2px solid #65CAFF;
				}
				&:nth-of-type(2){
					color:#ff551a;
					border: 2px solid #ff551a;
				}
			}
		}
	}
	
</style>
